﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ns
{
    public class FSMBase : MonoBehaviour
    {
        #region 脚本声明周期
        private void Start()
        {
            ConfigFSM();
            InitComponent();
            InitDefaultState();
        }
        public void Update()
        {
            Test_currentStateID = currentStateID;
            currentState.Reason(this);
            currentState.ActionState(this);
        }
        #endregion

        #region 状态机自身成员
        private FSMState currentState;
        private FSMState defaultState;
        private List<FSMState> states;
        [Tooltip("默认状态编号")]
        public FSMStateID defaultStateID;
        public FSMStateID currentStateID { get; private set; }
        [SerializeField]
        private FSMStateID Test_currentStateID;
        public string fileName="xxx.txt";
        private void InitDefaultState()
        {
            defaultState = states.Find(s => s.StateID == defaultStateID);
            currentState = defaultState;
            currentStateID = defaultStateID;
            currentState.EnterState(this);
        }
        private void ConfigFSM()
        {
            states = new List<FSMState>();
            var map = AIConfigurationReaderFactory.GetMap(fileName);
            foreach (var state in map)
            {
                Type type = Type.GetType("ns." + state.Key + "State");
                FSMState stateobj = Activator.CreateInstance(type) as FSMState;
                states.Add(stateobj);
                foreach (var list in state.Value)
                {
                    FSMTriggerID triggerID = (FSMTriggerID)Enum.Parse(typeof(FSMTriggerID), list.Key);
                    FSMStateID stateID = (FSMStateID)Enum.Parse(typeof(FSMStateID), list.Value);
                    stateobj.AddMap(triggerID, stateID);
                }
            }
        }
        public void ChangeActiveState(FSMStateID stateID)
        {
            currentState.ExitState(this);
            currentState = stateID == FSMStateID.Default ? defaultState : states.Find(s => s.StateID == stateID);
            currentStateID = stateID;
            currentState.EnterState(this);
        }
        #endregion

        #region 为状态和条件提供的外界成员
        [HideInInspector]
        public Animator animator;
        public void InitComponent()
        {
            animator = GetComponentInChildren<Animator>();
        }
        #endregion
    }
}